from mysql import DBUser, SessionLocal
from sqlalchemy.orm import Session
from fastapi import Depends, FastAPI
from pydantic import BaseModel
from typing import Optional
import uvicorn


app = FastAPI()


class User(BaseModel):
    id: Optional[int] = None
    username: str
    sex: Optional[str] = None
    login_time: Optional[int] = None

def get_db():
    db = SessionLocal()
    try:
        print('db连接')
        yield db
    finally:
        print('db关闭')
        db.close()


@app.post("/queryUser", response_model=User)
async def query_user(username: str, db: Session = Depends(get_db)):
    db_user = DBUser.get_by_username(db, username)
    if db_user:
        print(db_user)
        return db_user


if __name__ == '__main__':
    uvicorn.run(app, host="0.0.0.0", port=8000)